import pymysql

from config import DbConfig


def get_connection():
    return pymysql.connect(
        user=getattr(DbConfig, "DB_USER"),
        password=getattr(DbConfig, "DB_PASSWORD", ""),
        host=getattr(DbConfig, "DB_HOST"),
        port=getattr(DbConfig, "DB_PORT", 0),
        database=getattr(DbConfig, "DB_DATABASE")
    )


# db = get_connection()
class Mysql():

    def __init__(self, autocommit=False, cursor=None) -> None:
        self._autocommit = autocommit
        
        if cursor:
            self._cursor = cursor
        else:
            self._cursor = pymysql.cursors.DictCursor


    @property
    def cursor(self):
        return self._cursor

    @property
    def db(self):
        return self._db

    def __enter__(self):
        self._db = get_connection()
        self._db.autocommit(self._autocommit)

        self._cursor = self._db.cursor(self._cursor)
        return self

    def __exit__(self, *exc_info):
        del exc_info

        self._cursor.close()
        self._db.close()










# def execute(sql, *args):
#     with db.cursor() as cursor:
#         cursor.execute(sql)

#     db.commit()
#     return True


# def _getKeyAndValue(cls):
#     ks = []
#     vs = []

#     for k in cls.__dir__():
#         if (k[0:2] != "__") and (k[-2:] != "__") and (hasattr(cls, k)):
#             n = getattr(cls, k)
#             if n:
#                 ks.append("`"+k+"`")
#                 vs.append("`"+n+"`" if type(n) == str else n)
#     return tuple(ks), tuple(vs)


# def _getTableName(cls):
#     # return getattr(cls, "__tablename__", type(cls).__name__)
#     return "`"+getattr(cls, "__tablename__", type(cls).__name__)+"`"


# def delete(model):
#     try:
#         k, v = _getKeyAndValue(model)
#         w = ""
#         for i in range(len(k)):
#             w += "{}={} ".format(k[i], v[i])
#         sql = "DELETE FROM "+_getTableName(model)+" WHERE " + w + ";"
#         with db.cursor() as cursor:
#             cursor.execute(sql)
#         db.commit()
#         return True
#     except:
#         return False


# def insert(model):
#     k, v = _getKeyAndValue(model)
#     sql = "INSERT INTO " + _getTableName(model) + \
#         "("+",".join(k)+") VALUES("+("%s,"*len(v))[:-1]+");"

#     with db.cursor() as cursor:
#         cursor.execute(sql, v)
#     db.commit()


# def update(model):
#     k, v = _getKeyAndValue(model)

#     sql = "UPDATE " + _getTableName(model) + "SET"

#     return True


# def select(model, n=1):
#     # k, v = _getKeyAndValue(model)
#     sql = "SELECT * FROM "+_getTableName(model)
#     with db.cursor() as cursor:
#         cursor.execute(sql)
#         res = cursor.fetchmany(n)
#         return res


# def selectAll(model):
#     # k, v = _getKeyAndValue(model)
#     sql = "SELECT * FROM "+_getTableName(model)
#     with db.cursor() as cursor:
#         cursor.execute(sql)
#         res = cursor.fetchall()
#         return res

